package com.wanmait.wisdom.web.controller;

import com.wanmait.wisdom.entity.Resident;
import com.wanmait.wisdom.entity.ResidentType;
import com.wanmait.wisdom.util.AjaxResult;
import com.wanmait.wisdom.util.ValidateCodeUtils;
import com.wanmait.wisdom.util.web.WebJWTUtils;
import com.wanmait.wisdom.web.service.WebHouseService;
import com.wanmait.wisdom.web.service.WebResidentService;

import com.wanmait.wisdom.web.service.WebResidentTypeService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController

@RequestMapping("web")
public class WebResidentController {

    @Value("${token.expireMinutes}")
    private int expireMinutes;
    @Resource
    private WebResidentService webResidentService;
    @Resource
    private WebResidentTypeService webResidentTypeService;

    //用户名密码登录
    @PostMapping("login")
    public AjaxResult login(@RequestBody Resident resident, Boolean value,HttpServletRequest request){
        Resident loginResident = webResidentService.login(resident);
        if (loginResident != null){
            Map<String,String> claims = new HashMap<>();
            claims.put("phone1",loginResident.getPhone1());
            claims.put("name",loginResident.getName());
            String webToken = WebJWTUtils.createToken(loginResident.getId() + "", value ,expireMinutes, loginResident.getPassword(), claims);
            loginResident.setPassword(null);
            return AjaxResult.success("登录成功").put("resident",loginResident).put("webToken",webToken);
        }
        return AjaxResult.error(10001,"账号或密码错误");
    }
    //验证码登录
    //@PostMapping("loginByCode")
    //获取验证码
    @GetMapping("sendCode")
    public AjaxResult sendCode(String phone){
//        double randomValue = Math.random();
//        int result;
//        if (randomValue < 0.5) {
//            result = 4;
//        } else {
//            result = 6;
//        }
//        Integer sendCode = ValidateCodeUtils.generateValidateCode(result);
        Integer sendCode = 123456;
        //webResidentService.sendCode(phone,code+"");
        System.out.println("验证码为："+sendCode+"-----------------------------------------------------------");
        return AjaxResult.success("验证码发送成功").put("code",sendCode);
    }
    ///验证码成功后登录
    @PostMapping("loginWithPhone")
    public AjaxResult loginWithPhone(String phone, Boolean value){
        Resident resident = webResidentService.getResidentByPhone1(phone);
        if (resident != null){
            Map<String, String> claims = new HashMap<>();
            claims.put("name",resident.getName());
            claims.put("phone",resident.getPhone1());
            String webToken = WebJWTUtils.createToken(resident.getId() + "", value, expireMinutes, resident.getPassword(), claims);
            resident.setPassword(null);
            return  AjaxResult.success("登录成功").put("resident",resident).put("webToken",webToken);
        }
        return AjaxResult.error(10001,"账号或密码错误");
    }

    @GetMapping("addEmail")
    public void updateEmail(Integer id,String email){
        webResidentService.updateEmail(id,email);
    }
    @GetMapping("updatePhone1")
    public void updatePhone1(Integer id,String phone){
        webResidentService.updatePhone1(id,phone);
    }
    @GetMapping("updatePhone2")
    public void updatePhone2(Integer id,String phone2){
        webResidentService.updatePhone2(id,phone2);
    }
    //修改个人信息
//    @PostMapping("${id:\\d+}")
//    public AjaxResult getResidentById(@PathVariable() Integer id){
//        Resident resident = webResidentService.getResidentById(id);
//        return  null;
//    }
    //验证身份证正面
    @PostMapping("uploadCardPicFacade")
    public AjaxResult uploadCardPicFacade(MultipartFile file){
        try {
            String Path = ResourceUtils.getURL("classpath:").getPath()+"/static/uploadCardPicFacade";
            String fileName = UUID.randomUUID().toString() .replaceAll("-","")+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
            file.transferTo(new File(Path,fileName));
            return AjaxResult.success("上传成功").put("fileName",fileName);
        } catch (IOException e) {
            return AjaxResult.error("上传失败");
        }
    }
    //验证身份证反面
    @PostMapping("uploadCardPicBack")
    public AjaxResult uploadCardPicBack(MultipartFile file){
        try {
            String Path = ResourceUtils.getURL("classpath:").getPath()+"/static/uploadCardPicBack";
            String fileName = UUID.randomUUID().toString() .replaceAll("-","")+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
            file.transferTo(new File(Path,fileName));
            return AjaxResult.success("上传成功").put("fileName",fileName);
        } catch (IOException e) {
            return AjaxResult.error("上传失败");
        }
    }
    //验证照片
    @PostMapping("uploadPic")
    public AjaxResult uploadPic(MultipartFile file){
        try {
            String Path = ResourceUtils.getURL("classpath:").getPath()+"/static/uploadPic";
            String fileName = UUID.randomUUID().toString() .replaceAll("-","")+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
            file.transferTo(new File(Path,fileName));
            return AjaxResult.success("上传成功").put("fileName",fileName);
        } catch (IOException e) {
            return AjaxResult.error("上传失败");
        }
    }
    //根据居民id回去该居民类型
    @GetMapping("findType")
    public AjaxResult  getResidentType(Integer id){
        ResidentType residentType = webResidentTypeService.findById(id);
        return  AjaxResult.success("查询成功").put("residentType",residentType);
    }
    @GetMapping("updatePhoneCode")
    public AjaxResult updatePhoneCode(String phone){
        double randomValue = Math.random();
        int result;
        if (randomValue < 0.5) {
            result = 4;
        } else {
            result = 6;
        }
        Integer code = ValidateCodeUtils.generateValidateCode(result);
        webResidentService.sendCode2(phone,code+"");
//        Integer code = 123456;
        return AjaxResult.success("验证码发送成功").put("code",code);
    }

    //验证手机验证码
    @GetMapping("verifyCaptcha")
    public AjaxResult verifyCaptcha(Integer captcha,Integer inputCode){
        if (captcha.equals(inputCode)){
           return AjaxResult.success(true);
        }
        else{
            return AjaxResult.success(false);
        }
    }
    @GetMapping("verifyPhoneCode")
    public AjaxResult verifyCaptchaAndPhone(String phone,Integer captcha,Integer inputCode,Integer id){
        if (captcha.equals(inputCode)){
            webResidentService.updatePhone1(id,phone);
            return AjaxResult.success("修改成功");
        }
        else{
           return AjaxResult.error(100,"验证码错误");
        }
    }
    @GetMapping("verifyPhoneCode2")
    public AjaxResult verifyPhoneCode(String phone,Integer captcha,Integer inputCode,Integer id){
        if (captcha.equals(inputCode)){
            webResidentService.updatePhone2(id,phone);
            return AjaxResult.success("修改成功");
        }
        else{
            return AjaxResult.error(100,"验证码错误");
        }
    }



    @GetMapping("checkPhone")
    public AjaxResult checkPhone(String phone) {
        Integer count = webResidentService.getCountByPhone(phone);
        if (count >= 1) {
            return AjaxResult.error(100, "该手机号已存在");
        } else {
            return AjaxResult.success("该手机号可以使用");
        }
    }

}
